import Vue from 'vue'
import App from './App'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import VueRouter from 'vue-router'
import store from './vuex/store'
import Vuex from 'vuex'
import routes from './routes'
import 'font-awesome/css/font-awesome.min.css'
import axios from 'axios'
import '@/common/js/permission'


//配置axios的全局基本路径
axios.defaults.baseURL = 'http://localhost:8080';
//全局属性配置，在任意组件内可以使用this.$http获取axios对象
Vue.prototype.$http = axios

Vue.use(ElementUI)
Vue.use(VueRouter)
Vue.use(Vuex)

const router = new VueRouter({
  routes
})

//======================axios的前置拦截器【拦截调用后端的请求====================//
axios.interceptors.request.use(res=>{
  let token = localStorage.getItem("token");
  if(token){
    res.headers["token"] = token;
  }
  return res;//放行
},error => {
  Promise.reject(error)
})
//======================axios的前置拦截器【拦截调用后端的请求】====================//

//======================axios的后置拦截器【处理后台登录拦截的结果】====================//
axios.interceptors.response.use(res => {
  console.log("res:",res);//不知道响应拦截器,响应对象里面的内容,可以打印查看
  if (false === res.data.success && "toLogin" === res.data.message) {
    localStorage.clear();//相当于退出登录逻辑,令牌没有或者无效,需要清理本地缓存,然后路由跳转到登录页↓
      
    router.push({path: '/login'});//路由跳转到登录页↑
  }
  return res;
},error => {
  Promise.reject(error)
})
//======================axios的后置拦截器【处理后台登录拦截的结果】====================//

//======================路由的前端拦截器【拦截不到后端的请求】====================//
router.beforeEach((to, from, next) => {
  //如果要去的路径,是登录页面或注册页面,那就放行
  if (to.path == '/login' || to.path == "/register") {
    next();//放行
  }else{//其他页面都需要判断你是否登录过
    //获取localStorage的登录信息
    let token = localStorage.getItem('token');
    if (token) {
      next(); //登录过放行
    } else {
      next({path: '/login'});//跳转到login - 登录页面
    }
  }
})
//处理页面刷新动态路由失效问题
initIndexRouters();

function initIndexRouters(){
    if(!localStorage.menus){
        return;
    }
    
    //防止重复配置路由：4就是main.js中路由的个数 - 如果你的静态路由是6个这里要写成6
    if(router.options.routes.length>4){
        return;
    }
    
    let menus = localStorage.getItem('menus');
    menus = JSON.parse(menus);
    
    let tempRouters = [];
    
    menus.forEach(menu=>{
        let indexRouter = {
            path: '/',
            iconCls: menu.icon,
            name: menu.name,
            component: resolve => require(['@/views/Home'], resolve),
            children: []
        }
        menu.children.forEach(cMenu=>{
            let cr = {
                path: cMenu.url,
                name: cMenu.name,
                component: resolve => require(['@/views/'+cMenu.component], resolve)
            }
            indexRouter.children.push(cr)
        })
        tempRouters.push(indexRouter)
        router.options.routes.push(indexRouter)
    })
    //动态路由配置
    router.addRoutes(tempRouters);
}

//每次路由之前都要执行,每次请求都要经过路由
//每次请求都不拦截到
router.beforeEach((to, from, next) => {
  //NProgress.start();
  if (to.path == '/login') {
    //重新登录,把原来session移除掉
    localStorage.removeItem('realName');
    localStorage.removeItem('userPic');
  }
  next();
})

new Vue({
  router,
  store,
  render: h => h(App) // index.html id为app的div标签下面使用<App/>和template: '<App/>',一样的效果
}).$mount('#app') // 和el: '#app'效果一样都是挂载在index.html id为app的div标签上面

